﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PPIDesktopClient.General;
using PPIDesktopClient.General;
using PPIDesktopClient.Entities;
using System.IO;
using PPIDesktopClient.Logic;

namespace PPIDesktopClient.Controls.Downloader
{
    public partial class Downloader : UserControl
    {
        private int m_TotalImages = 0;
        private XMLHelperDownloadImage m_XMLImage;
        private bool m_Stopped = false;

        public Downloader()
        {
            InitializeComponent();
            HideShowControls(false);

        }

        private delegate void HideShowControlsCallback(bool status);

        private void HideShowControls(bool status)
        {
            if (this.InvokeRequired)
            {
                HideShowControlsCallback d = new HideShowControlsCallback(HideShowControls);
                this.Invoke(d, new object[] { status });
            }
            else
            {
                foreach (Control c in this.Controls)
                {
                    c.Visible = status;
                }
            }
        }

        public void StartDownload()
        {
            if (!m_BackgroundWorkerDownloader.IsBusy)
            {
                m_BackgroundWorkerDownloader.RunWorkerAsync();
                m_Stopped = false;
            }
            
        }

        public void StopDownload()
        {
            m_BackgroundWorkerDownloader.CancelAsync();
            m_Stopped = !m_Stopped;
            if (m_Stopped)
                this.btnStop.Image = global::PPIDesktopClient.Properties.Resources.Play;
            else
                this.btnStop.Image = global::PPIDesktopClient.Properties.Resources.Stop;

        }
            
        private void m_BackgroundWorkerDownloader_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = (BackgroundWorker)sender;
            if (bw.CancellationPending)
            {
                e.Cancel = true;
            }
            Download(e);

        }

        private void Download(DoWorkEventArgs e)
        {
            m_XMLImage = new XMLHelperDownloadImage(Constants.k_XmlImagePath);
            int m_offset = m_XMLImage.GetLastImageID();
            List<EVendor_Visit_XMissionStructures_Image> _ImageList = LVendor_Visit_XMissionStructures_Image.GetServerImages(m_offset);
            HideShowControls(true);
            CalculateAmountImages(_ImageList);
            int _CountImages = m_TotalImages;
            string _DestinationImagePath = "";
            foreach (EVendor_Visit_XMissionStructures_Image _Image in _ImageList)
            {
                if (m_BackgroundWorkerDownloader.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
                _DestinationImagePath = DirHelper.CreateVisitDirectory(_Image.Asset.Id, Constants.K_ImageCachePath);
                _DestinationImagePath += Path.DirectorySeparatorChar + _Image.FileName;
                byte[] _ByteImage;
                if (!File.Exists(_DestinationImagePath))
                {
                    _ByteImage = _Image.GetImageBytes();
                    ImagesHelper.CreateImageFromBytes(_ByteImage, _DestinationImagePath);
                    _CountImages--;
                    m_BackgroundWorkerDownloader.ReportProgress(ReportProgress(_CountImages));
                    m_XMLImage.AddImageNode(_Image.Asset.Id, _Image.Id, _Image.FileName, _DestinationImagePath);
                    m_XMLImage.Save();
                }
            }
        }

        private int ReportProgress(int _CountUploaded)
        {
            int _Progress;
            try
            {
                _Progress = ((m_TotalImages - _CountUploaded) * 100) / m_TotalImages;
            }
            catch (Exception)
            {
                _Progress = 0;
            }
            return _Progress;
        }

        private void CalculateAmountImages(List<EVendor_Visit_XMissionStructures_Image> _ImageList)
        {
            string _DestinationImagePath;
            foreach (EVendor_Visit_XMissionStructures_Image _Image in _ImageList)
            {
                _DestinationImagePath = DirHelper.CreateVisitDirectory(_Image.Asset.Id, Constants.K_ImageCachePath);
                _DestinationImagePath += Path.DirectorySeparatorChar + _Image.FileName;
                if (!File.Exists(_DestinationImagePath))
                {
                    m_TotalImages++;
                }
            }
        }

        private void m_BackgroundWorkerDownloader_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            int countUploaded = (((((e.ProgressPercentage * m_TotalImages) / 100) - m_TotalImages) * -1) - m_TotalImages) * -1;
            if (countUploaded != m_TotalImages)
                countUploaded++;
            lblShowStats.Text = (countUploaded) + " / " + m_TotalImages.ToString();

            progressBarDownloader.Value = e.ProgressPercentage;
        }

        private void m_BackgroundWorkerDownloader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBarDownloader.Value = 0;
            m_TotalImages = 0;
            lblShowStats.Text = "";
            if (!e.Cancelled)
            {
                HideShowControls(false);
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (m_Stopped)
                StartDownload();
            else
                StopDownload();
        }
    }
}
